package Day27;

/**
 * ----------------------------------------------------------------------------------------------------
 * 题目：
 *      有个内含单词的超大文本文件，给定任意两个不同的单词，找出在这个文件中这两个单词的最短距离(相隔单词数)。
 *      如果寻找过程在这个文件中会重复多次，而每次寻找的单词不同，你能对此优化吗?
 * ----------------------------------------------------------------------------------------------------
 * 示例：
 *      输入：
 *          words = ["I","am","a","student","from","a","university","in","a","city"],
 *          word1 = "a",
 *          word2 = "student"
 *      输出：1
 * ----------------------------------------------------------------------------------------------------
 * 方法：
 *      双指针
 * ----------------------------------------------------------------------------------------------------
 */
class Solution {
    public static void main(String[] args) {
        String[] words = new String[]{"I","am","a","student","from","a","university","in","a","city"};
        String word1 = "a";
        String word2 = "student";
        System.out.println(findClosest(words,word1,word2));
    }
    public static int findClosest(String[] words, String word1, String word2) {
        int i = -100000;
        int j = 100000;
        int min = Integer.MAX_VALUE;
        for(int k=0;k<words.length;++k){
            if(words[k].equals(word1)){
                i=k;
            }
            if(words[k].equals(word2)){
                j=k;
            }
            min = Math.min(min,Math.abs(i-j));
        }
        return min;
    }
}